﻿
public static class FileCopyHelper
{
   
     name="sourceDir">源文件夹路径</param>
     name="targetDir">目标文件夹路径</param>
     name="threadCount">线程数（建议1-8，默认4）</param>
    public static async Task CopyDirectoryAsync(string sourceDir, string targetDir, int threadCount = 4)
    {
        if (!Directory.Exists(sourceDir))
            throw new DirectoryNotFoundException("源文件夹不存在：" + sourceDir);
        Directory.CreateDirectory(targetDir);
        Console.WriteLine($"开始拷贝：{sourceDir} → {targetDir}（线程数：{threadCount}）");
        string[] allFiles = Directory.GetFiles(sourceDir, "*.*", SearchOption.AllDirectories);
        SemaphoreSlim semaphore = new SemaphoreSlim(threadCount, threadCount);

        try
        {
          
            Task[] copyTasks = Array.ConvertAll(allFiles, async file =>
            {
                await semaphore.WaitAsync(); 
                try
                {
                    string relativePath = Path.GetRelativePath(sourceDir, file);
                    string targetFile = Path.Combine(targetDir, relativePath);
                    Directory.CreateDirectory(Path.GetDirectoryName(targetFile));
                    using FileStream sourceStream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, FileOptions.SequentialScan);
                    using FileStream targetStream = new FileStream(targetFile, FileMode.Create, FileAccess.Write, FileShare.None, 4096, FileOptions.SequentialScan);
                    await sourceStream.CopyToAsync(targetStream); 

                    Console.WriteLine($"拷贝完成：{Path.GetFileName(file)}");
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"拷贝失败：{file} → 错误：{ex.Message}");
                }
                finally
                {
                    semaphore.Release(); 
                }
            });

            await Task.WhenAll(copyTasks); 
            Console.WriteLine("\n所有文件拷贝完成！");
        }
        finally
        {
            semaphore.Dispose();
        }
    }
}

class Program
{
    static async Task Main(string[] args)
    {
       
        string sourceDirectory = @"D:\TestSource"; 
        string targetDirectory = @"D:\TestTarget"; 
        int threadCount = 4; 

        try
        {
            DateTime start = DateTime.Now;
            await FileCopyHelper.CopyDirectoryAsync(sourceDirectory, targetDirectory, threadCount);
            TimeSpan cost = DateTime.Now - start;
            Console.WriteLine($"总耗时：{cost.TotalSeconds:F2} 秒");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"拷贝异常：{ex.Message}");
        }

        Console.ReadKey();
    }
}